/*********************************************************************************
 *      Copyright:  (C) 2025 LingYun<iot25@lingyun>
 *                  All rights reserved.
 *
 *       Filename:  thread1.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(22/03/25)
 *         Author:  LingYun <iot25@lingyun>
 *      ChangeLog:  1, Release initial version on "22/03/25 18:35:45"
 *                 
 ********************************************************************************/
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<unistd.h>

int main( int argc, char **argv)
{
	int             	share_var= 1000;
	pthread_t			tid;
	pthread_attr_t		thread_attr;

	if( pthread_attr_init(&thread_attr) )
	{
		printf("pthread_attr_init() failure: %s\n", strerror(errno));
		return -1;
	}

	if( pthread_attr_setstacksize(&thread_attr, 120*1024) )
	{
		printf(" pthread_attr_setstacksize() failure: %s\n",strerror(errno));
		return -2;
	}

	if( pthread_attr_setdetachstate(&thread_attr,PTHREAD_CREATE_DETACHED))
	{
		printf(" pthread_attr_setdetachstate() failure: %s\n",strerror(errno));
		return -3;
	}

	pthread_create(&tid , &thread_attr , thread_worker1 , &share_var);
	printf(" thread worker1 tid[%ld] create ok\n",tid);

	pthread_create(&tid , NULL , thread_worker2 , &share_var);
    printf(" thread worker2 tid[%ld] create ok\n",tid);
	
	pthread_attr_destory(&thread_attr);

	pthread_join(tid, NULL);

	while(1)
	{
		printf(" man/control thread share_var: %d\n", share_var);
		sleep(10);
	}

}

void *thread_worker1(void *args)
{
	int 			*ptr = (int *)args;

	if( !args )
	{
		printf(" %s() invalid argument\n",__FUNCTION__);
		pthread_exit(NULL);

	}
	printf(" thread worker1 [%ld] start running...\n",pthread_self() );

	while(1)
	{
		printf(" +++: %s before share_var++: %d\n",__FUNCTION__, *ptr);
		*ptr +=1;
		sleep(2);
		printf(" +++: %s after sleep share_var: %d\n",__FUNCTION__,*ptr);

		
	}
	printf("thread worker 1 exit...\n");

	return NULL;

}
void *thread_worker2(void *args)
  {
      int             *ptr = (int *)args;

      if( !args )
      {
          printf(" %s() invalid argument\n",__FUNCTION__);
          pthread_exit(NULL);

      }
      printf(" thread worker1 [%ld] start running...\n",pthread_self() );

      while(1)
      {
          printf(" ---: %s before share_var--: %d\n",__FUNCTION__, *ptr);
          *ptr +=1;
          sleep(2);
          printf(" ---: %s after sleep share_var: %d\n",__FUNCTION__,*ptr);


      }
      printf("thread worker 2 exit...\n");

      return NULL;

}
